package com.xywl.escort.view.pwd

import android.os.Bundle
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.bean.UpdateLoginPwdReq
import com.xywl.escort.common.Constant
import com.xywl.escort.common.Constant.EventMessage.FINISH_ACTIVITY
import com.xywl.escort.common.Constant.EventType.EVENT_MODIFY_LOGIN_PWD_TYPE
import com.xywl.escort.common.PreferenceKeys
import com.xywl.escort.common.PreferenceKeys.USER_ID
import com.xywl.escort.utils.MD5
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_modify_pwd.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.util.regex.Pattern
import javax.inject.Inject

@Route(path = "/xy/pwd/modify")
class ModifyPwdActivity : BaseActivity(), ModifyPwdContract.View {
    @Autowired
    @JvmField
    var type = 1

    @Inject
    lateinit var mPresenter: ModifyPwdContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_modify_pwd)
        ARouter.getInstance().inject(this)

        mPresenter.takeView(this)
        initView()
        addListener()

        EventBus.getDefault().register(this)
        // ARouter.getInstance().build("/xy/pwd/setting/pay").navigation()
    }

    private fun initView() {
        showBackButton()
        Timber.tag("ModifyPwdActivity").e("登录密码变更")
        setTitleText("更换登录密码")
    }

    private fun addListener() {
        text_recover_pwd.setOnClickListener {
            ARouter.getInstance().build("/xy/pwd/recover").navigation()
        }

        btn_confirm.setOnClickListener {
            val oldPwd = edit_old_pwd.text.toString().trim()
            val newPwd = edit_new_pwd.text.toString().trim()
            val confirmPwd = edit_confirm_pwd.text.toString().trim()

            if (checkLoginPwd(oldPwd, newPwd, confirmPwd)) {
                modifyLoginPwd(oldPwd, newPwd)
            }
        }
    }

    private fun checkLoginPwd(oldPwd: String, newPwd: String, confirmPwd: String): Boolean {
        val regex = "^(?=.*[a-zA-Z])(?=.*[0-9])[0-9A-Za-z!@~#\$%^&*()-+_`~,./=?\\\\|]{8,20}\$"
        if (TextUtils.isEmpty(oldPwd)) {
            ToastUtil.showTip(this, R.string.user_account_hint_old_password)
            return false
        } else if (TextUtils.isEmpty(newPwd) || TextUtils.isEmpty(confirmPwd)) {
            ToastUtil.showTip(this, R.string.user_account_hint_new_password)
            return false
        } else if (newPwd != confirmPwd) {
            ToastUtil.showTip(this, R.string.user_account_hint_password_error)
            return false
        } else if (newPwd.length < Constant.Length.MIN_LOGIN_PWD_LENGTH) {
            ToastUtil.showTip(this, R.string.user_account_reset_password_error)
            return false
        } else if (!Pattern.matches(regex, newPwd)) {
            ToastUtil.showTip(this, R.string.user_password_format_error)
            return false
        }
        return true
    }

    private fun modifyLoginPwd(oldPwd: String, newPwd: String) {
        val req = UpdateLoginPwdReq()
        req.id = RxSPTool.getString(this, USER_ID)
        req.oldLoginPwd = MD5.encrypt(oldPwd)
        req.newLoginPwd = MD5.encrypt(newPwd)
        mPresenter.modifyLoginPwd(req)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("ModifyPwdActivity").e("event.message=" + event.message)
        Timber.tag("ModifyPwdActivity").e("event.type=" + event.type)
        when (event.type) {
            EVENT_MODIFY_LOGIN_PWD_TYPE -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == FINISH_ACTIVITY) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun modifyLoginSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "修改登录密码成功")
        clearUserInfo()

        EventBus.getDefault().post(MessageEvent(EVENT_MODIFY_LOGIN_PWD_TYPE, FINISH_ACTIVITY))
        finish()
    }

    override fun modifyLoginFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    private fun clearUserInfo() {
        RxSPTool.clearPreference(this, PreferenceKeys.USER_ID)
        RxSPTool.clearPreference(this, PreferenceKeys.TOKEN)
        RxSPTool.clearPreference(this, PreferenceKeys.PHONE)
        RxSPTool.clearPreference(this, PreferenceKeys.NICK_NAME)
        RxSPTool.clearPreference(this, PreferenceKeys.HEAD_IMG)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
